local json = require "cjson"

--返回数据方法
local function responseMsg(code, msg, data)
    local rtn = {}
    rtn['code'] = code
    rtn['msg'] = msg
    rtn['data'] = data
    return json.encode(rtn)
end

--验证参数
local arg = ngx.req.get_uri_args()
local key = arg.key
if not key or #key <= 0 then
    ngx.say(responseMsg('2000', 'key为必填参数', nil))
    return
end

--连接redis
local redis = require "resty.redis"
red = redis:new()
--local ok, err = red:connect("127.0.0.1", 6379)   --连接redis   本机
local ok, err = red:connect("zljsz-testenvironmentdb.redis.rds.aliyuncs.com", 6379)   --连接redis  外网测试
--local ok, err = red:connect("zljsz-testenvironmentdbvpc.redis.rds.aliyuncs.com", 6379)   --连接redis  内网测试
--local ok, err = red:connect("zljsz-redis1dbvpc.redis.rds.aliyuncs.com", 6379)   --连接redis   正式
if not ok then
    ngx.say(responseMsg('1000', json.encode(err), nil))
    return
end

--连接redis密码
ok, err = red:auth('lzWu9gskZ9OQrnOP')   --连接redis  测试
--ok, err = red:auth('JtS42CKZsepk88EX')   --连接redis  正式

if not ok then    -- 链接失败的时候
    ngx.say(responseMsg('1001', json.encode(err), nil));
    return
end
red:select(1)

local cacheKey = "jqq:metadata"
local dataString = red:hget(cacheKey, key)
if dataString == ngx.null then
    ngx.say(responseMsg("2001", "key不存在", nil))
    return
end

data = json.decode(dataString)
ngx.header.content_type = "application/json"
ngx.say(responseMsg("1", "", data))
return
